package cn.agiledata.bank.common.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.springframework.dao.DataAccessException;

import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountLimit;
import cn.agiledata.bank.hibernateBean.AccountMessage;
import cn.agiledata.bank.hibernateBean.EsPrePayTrans;
import cn.agiledata.bank.hibernateBean.MessageCustomization;
import cn.agiledata.bank.hibernateBean.ScoresRules;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.Sysbook;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.hibernateBean.TransactionHis;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import cn.agiledata.bank.scores.service.IScoresService;
import cn.agiledata.bank.scores.service.ScoresFactory;
import cn.agiledata.bank.transaction.exception.TransactionException;
import cn.agiledata.bank.transaction.service.GetTransaction;
import cn.agiledata.bank.transaction.service.GetTransactionImpl;
import cn.agiledata.bank.transaction.service.TransactionFactory;
import com.vnv.infrastructure.logic.IPBAppFactory;
import com.vnv.infrastructure.logic.IPBHibernate3BaseMgr;
import com.vnv.infrastructure.logic.IPBMgrFactory;

public class TransactionTemplate extends IPBHibernate3BaseMgr {
    /**
     * 阌熸枻鎷烽敓绲燿阌熺煫纰夋嫹阌熸枻鎷峰簲transaction
     * 
     * @param id
     * @return
     */
    protected IMySpaceService getMySpaceService() {
        return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
    }

    public Transaction getTransaction(String id) {
        Object o = null;
        if (id != null)
            o = getHibernateTemplate().find("from Transaction where id=?",
                    new Object[] { new Long(id) }).get(0);
        // o= getHibernateTemplate().get(Transaction.class, new Long(id));
        if (o != null)
            return (Transaction) o;
        return new Transaction();
    }

    public Transaction getTransactionByVerifyCode(String verifyCode) {
        Object o = null;
        if (verifyCode != null)
            o = getHibernateTemplate().find(
                    "from Transaction where verifyCode=?",
                    new Object[] { verifyCode }).get(0);
        if (o != null)
            return (Transaction) o;
        return null;
    }

    /**
     * 阌熸枻鎷烽敓绲玶anId阌熺煫纰夋嫹阌熸枻鎷峰簲transaction
     * 
     * @param id
     * @return
     */
    public Transaction getTransactionByTranId(String tranId) {
        Object o = null;
        if (tranId != null)
            o = getHibernateTemplate().find("from Transaction where transId=?",
                    new Object[] { tranId });
        // o= getHibernateTemplate().get(Transaction.class, new Long(id));
        if (o != null && ((List) o).size() > 0)
            return (Transaction) ((List) o).get(0);
        else {
            try {
            	List list = getHibernateTemplate().find("from Transaction where id=?",
                        new Object[] { new Long(tranId) });
            	if(list.size()==0)
            		return null;
            	else
            	  o	= list.get(0);
               
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return (Transaction) o;
    }

    public TransactionHis getTransactionHis(String tranId) {
        Object o = null;
        if (tranId != null) {
            o = getHibernateTemplate()
                    .find(
                            "from TransactionHis where transId=? order by updateTime desc",
                            new Object[] { tranId });
        }
        // if (o != null && ((List) o).size() > 1)
        // return (TransactionHis) ((List) o).get(1);
        // else
        // o = getHibernateTemplate()
        // .find(
        // "from TransactionHis where transId=? order by updateTime desc",
        // new Object[] { tranId });
        TransactionHis his = null;
        List list = (List) o;
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                his = (TransactionHis) list.get(i);
                if (his.getTransStatus().equals(
                        Constant.TRANS_STATUS_WAITFORBUYER)) {
                    break;
                }
                if (his.getTransStatus().equals(
                        Constant.TRANS_STATUS_WAITFORBUYERAFFIRM)) {
                    break;
                }
            }
        }
        return his;
    }

    /**
     * 
     * @param tranId
     *            阌熸枻鎷烽敓阒舵唻鎷烽敓锟?
     * @param ifSuccess
     *            阌熻鍑ゆ嫹鏅掗敓锟?
     * @param bankBackCode
     *            阌熸枻鎷烽敓鍙嚖鎷烽敓鏂ゆ嫹阌熸枻鎷?
     */
    public void saveTransactionByParameter(String tranId, String ifSuccess,
            String bankBackCode) {
        Transaction tran = getTransactionByTranId(tranId);
        if (isAffirmedTransaction(tran))
            return;
        tran.setInsideStatus(ifSuccess);
        tran.setBankResponse(bankBackCode);
        if (Constant.INSIDE_STATUS_YES.equals(ifSuccess)) {
            tran.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
        } else {
            tran.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONFAIL);
        }
        tran.setEndDate(new Date());
        GetTransaction getTran = new GetTransactionImpl();
        TransactionFactory tt = getTran.getTransaction(Constant.ACTION_TYPE_A);
        try {
            tt.saveTransaction(tran);
        } catch (RuntimeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public Transaction saveTransactionByFirstStep(Account account,
            Double amount, String bankID, String sellerURL, String orderid) {

        Transaction tran = new Transaction();
        try {
            ActionTypeTemplate att = (ActionTypeTemplate) IPBMgrFactory
                    .getMgr("actionTypeTemplate");

            AccountTemplate at = (AccountTemplate) IPBMgrFactory
                    .getMgr("accountTemplate");
            tran.setDebit(at.getBankSubAccount());
            tran.setActionType(att.getActionTypeById(Long
                    .parseLong(Constant.ACTION_TYPE_C)));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        tran.setTransId(UniqueIdentityUtil.getTransactionSequence());
        tran.setCredit(account.getDefaultSubAccount());
        // 阌熸枻鎷疯阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷烽敓鑺傜尨鎷烽敓镌潻鎷烽敓鏂ゆ嫹阌熸枻鎷?
        WeatherUtil.fillCreateAndUpdateInfo(tran, account.getAccountId());
        tran.setBeginDate(new Date());
        // 阌熸枻鎷烽敓鏂ゆ嫹钟舵€?
        tran.setTransStatus(Constant.TRANS_STATUS_INIT);
        // 阌熸枻鎷烽敓阒舵枻鎷烽敓锟?
        tran.setAmount(amount);
        tran.setBankSeq(new Long(bankID));
        // 阌熸枻鎷烽敓鏂ゆ嫹涓€阌熸枻鎷烽敓鏂ゆ嫹阌熼ズ鎲嬫嫹阌熸枻鎷烽敓鏂ゆ嫹阌熺但ransaction阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹瀹炶浆阌熷圹璇ф嫹阌熸枻鎷?
        tran.setInsideStatus(Constant.INSIDE_STATUS_NO);

        tran.setTradeType(Constant.TRADE_TYPE_NOASSURE);
        tran.setSellerUrl(sellerURL);
        tran.setOrderId(orderid);
        GetTransaction getTran = new GetTransactionImpl();
        TransactionFactory tt = getTran.getTransaction(Constant.ACTION_TYPE_A);
        try {
            tt.saveTransaction(tran);
        } catch (RuntimeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return tran;
    }

    /**
     * 鐩撮敓鎺ラ潻鎷烽敓绛嬩缭阌熸枻鎷?
     * 
     * @param debit
     *            阌熸枻鎷烽敓鏂ゆ嫹
     * @param credit
     *            阌熸枻鎷烽局
     * @param account
     *            阌熸枻鎷烽敓锟?
     * @param Orderid
     * @return
     */
    public Transaction saveBussinessTransactionNoAssure(SubAccount debit,
            SubAccount credit, Double account, String Orderid) throws Exception {

        Transaction tran = capeTran(debit, credit, account, Orderid,
                Constant.TRADE_TYPE_NOASSURE,
                Constant.TRANS_STATUS_TRANSACTIONSUCCESS,
                Constant.MODEL_TYPE_GATHERING, Constant.ACTION_TYPE_C);

        return tran;
    }

    /**
     * 阌熸枻鎷锋伅鏀敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹
     * 
     * @param debit
     *            阌熺煫浼欐嫹阌熸枻鎷烽敓鍓夸紮鎷?
     * @param credit
     *            阌熻妭璇ф嫹阌熷圹浼欐嫹
     * @param account
     *            阌熸枻鎷锋伅阌熸枻鎷烽敓锟?
     * @return 阌熸枻鎷烽敓鏂ゆ嫹(pojo)阌熸枻鎷烽敓鏂ゆ嫹
     */
    public Transaction saveBussinessTransactionInterest(SubAccount debit,
            SubAccount credit, Double account) throws Exception {

        Transaction tran = capeTran(debit, credit, account, null,
                Constant.TRADE_TYPE_NOASSURE,
                Constant.TRANS_STATUS_TRANSACTIONSUCCESS,
                Constant.MODEL_TYPE_INTEREST, Constant.ACTION_TYPE_J);

        return tran;
    }

    private Transaction capeTran(SubAccount debit, SubAccount credit,
            Double account, String Orderid, String tradeType,
            String tranStatus, String modelType, String actionType) {
        Transaction tran = new Transaction();
        ActionTypeTemplate att;

        att = (ActionTypeTemplate) IPBMgrFactory.getMgr("actionTypeTemplate");
        // actionType
        tran.setActionType(att.getActionTypeById(Long.parseLong(actionType)));

        tran.setBeginDate(new Date());
        // 阌熸枻鎷烽敓绛嬫柟
        tran.setDebit(debit);
        // 阌熺Ц娆炬柟
        tran.setCredit(credit);
        tran.setTransId(UniqueIdentityUtil.getTransactionSequence());
        // 阌熸枻鎷烽敓阒舵枻鎷烽敓锟?
        tran.setAmount(account);

        // 阌熸枻鎷疯阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷烽敓鑺傜尨鎷烽敓镌潻鎷烽敓鏂ゆ嫹阌熸枻鎷?
        WeatherUtil.fillCreateAndUpdateInfo(tran, debit.getAccount()
                .getAccountId());
        tran.setTradeType(tradeType);
        tran.setTransStatus(tranStatus);
        tran.setOperate(Constant.MODEL_TYPE_PAYMONEY);
        tran.setOrderId(Orderid);
        // 阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷锋伅
        GetTransaction getTran = new GetTransactionImpl();
        TransactionFactory tt = getTran.getTransaction(actionType);
        tt.saveTransaction(tran);
        return tran;
    }

    public Transaction saveBussinessTransactionAssure(SubAccount debit,
            SubAccount credit, Double account, String Orderid) throws Exception {
        Transaction tran = capeTran(debit, credit, account, Orderid,
                Constant.TRADE_TYPE_ASSURE, Constant.TRANS_STATUS_INIT,
                Constant.MODEL_TYPE_GATHERING, Constant.ACTION_TYPE_C);
        return tran;
    }

    public boolean saveFinalStep(String tranId) {
        Transaction tran = getTransactionByTranId(tranId);
        if (tran.getTransStatus().equals(
                Constant.TRANS_STATUS_TRANSACTIONSUCCESS)) {
            return false;
        }
        boolean result = true;
        tran.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
        tran.setOperate(Constant.MODEL_TYPE_GATHERING);
        // 阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷锋伅
        GetTransaction getTran = new GetTransactionImpl();
        TransactionFactory tt = getTran.getTransaction(Constant.ACTION_TYPE_C);
        tt.saveTransaction(tran);

        return result;
    }

    public Transaction getTransactionByOrderIdAndAccountId(String orderId,
            String accountId) {
        List result = getHibernateTemplate()
                .find(
                        "from Transaction t where t.orderId=? and t.credit.account.accountId=?",
                        new Object[] { orderId, accountId });
        if (result != null && result.size() > 0) {
            Transaction tran = (Transaction) result.get(0);
            return tran;
        } else
            return null;
    }

    public Sysbook getSysbookByid(String id, String typeId) {
        return (Sysbook) this.getHibernateTemplate().find(
                " from Sysbook where id.listId=? and id.typeId=?",
                new Object[] { id, typeId }).get(0);
    }

    private String getHqlByOrderIdRange(List params, String accountId,
            String beginOrderId, String endOrderId, String transStatus) {
        String hql = "from Transaction t where t.credit.account.accountId=? ";
        params.add(accountId);
        if (beginOrderId != null && beginOrderId.length() > 0) {
            hql += "and t.orderId>=? ";
            params.add(beginOrderId);
        }
        if (endOrderId != null && endOrderId.length() > 0) {
            hql += "and t.orderId<=? ";
            params.add(endOrderId);
        }
        if (transStatus != null && transStatus.length() > 0) {
            hql += "and t.transStatus=? ";
            params.add(transStatus);
        }
        return hql;
    }

    public long getTransactionsTotalByOrderIdRange(String accountId,
            String beginOrderId, String endOrderId, String transStatus) {
        List params = new ArrayList();
        String hql = getHqlByOrderIdRange(params, accountId, beginOrderId,
                endOrderId, transStatus);
        hql = "select count(*) " + hql;
        List resultList = getHibernateTemplate().find(hql,
                params.toArray(new Object[0]));
        return ((Long) resultList.get(0)).longValue();
    }

    public List getTransactionsByOrderIdRange(String accountId,
            String beginOrderId, String endOrderId, String transStatus,
            int maxPerPage, int pageNo) {
        List params = new ArrayList();
        String hql = getHqlByOrderIdRange(params, accountId, beginOrderId,
                endOrderId, transStatus);
        Query query = getSession().createQuery(hql);
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        query.setFirstResult(maxPerPage * (pageNo - 1));
        query.setMaxResults(maxPerPage);
        return query.list();
    }

    private String getHqlByTimeRange(List params, String accountId,
            Date beginTime, Date endTime, String transStatus) {
        String hql = "from Transaction t where t.credit.account.accountId=? ";
        params.add(accountId);
        if (beginTime != null) {
            hql += "and t.beginDate>=? ";
            params.add(beginTime);
        }
        if (endTime != null) {
            hql += "and t.beginDate<=? ";
            params.add(endTime);
        }
        if (transStatus != null && transStatus.length() > 0) {
            hql += "and t.transStatus=? ";
            params.add(transStatus);
        }
        return hql;
    }

    public long getTransactionsTotalByTimeRange(String accountId,
            Date beginTime, Date endTime, String transStatus) {
        List params = new ArrayList();
        String hql = getHqlByTimeRange(params, accountId, beginTime, endTime,
                transStatus);
        hql = "select count(*) " + hql;
        List resultList = getHibernateTemplate().find(hql,
                params.toArray(new Object[0]));
        return ((Long) resultList.get(0)).longValue();
    }

    public List getTransactionsByTimeRange(String accountId, Date beginTime,
            Date endTime, String transStatus, int maxPerPage, int pageNo) {
        List params = new ArrayList();
        String hql = getHqlByTimeRange(params, accountId, beginTime, endTime,
                transStatus);
        Query query = getSession().createQuery(hql);
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        query.setFirstResult(maxPerPage * (pageNo - 1));
        query.setMaxResults(maxPerPage);
        return query.list();
    }

    public AccountLimit getAcctlimit(Account account) {
        AccountLimit al;
        al = getMySpaceService().getAcctlimitByAcctId(account.getId() + "");
        if (al == null)
            // al =
            // getMySpaceService().getAcctlimitByAcctGrading(account.getGrading().getId()+"");
            al = getMySpaceService().getAcctlimitByAcctGrading(account);

        return al;
    }

    public boolean ifHigher(Account account, double amount, AccountLimit al) {

        double allamount = account.getSumAmount().doubleValue() + amount;
        // double alltranamount;
        // if (account.getTranAmount() != null) {
        // alltranamount = account.getTranAmount().doubleValue() + 1;
        // } else {
        // alltranamount = 1;
        // }
        // if (eachamount > al.getEachlimit().doubleValue()
        // || alltranamount > al.getTranamount().doubleValue()
        // allamount > al.getAlllimit().doubleValue()) {
        // return true;
        // } else {
        // return false;
        // }
        return allamount > al.getAlllimit().doubleValue();
    }

    public boolean ifEachHigher(Account account, double eachamount,
            AccountLimit al) {
        if (eachamount > al.getEachlimit().doubleValue()) {
            return true;
        } else {
            return false;
        }

    }

    public long getCountOfBankCardTransactions(Account account) {
        String hql = "select count(*) from Transaction t where "
                + "((t.actionType.id=? and t.credit.account=?)" + " or "
                + "(t.actionType.id=? and t.debit.account=?))"
                + " and t.transStatus=? and t.insideStatus=?";
        List resultList = getHibernateTemplate().find(
                hql,
                new Object[] { Long.valueOf(Constant.ACTION_TYPE_A), account,
                        Long.valueOf(Constant.ACTION_TYPE_D), account,
                        Constant.TRANS_STATUS_TRANSACTIONSUCCESS,
                        Constant.INSIDE_STATUS_YES });
        return ((Long) resultList.get(0)).longValue();
    }

    public List getTransactionsByFuzzyTransId(String fuzzyTransId) {
        String hql = "from Transaction t where t.transId like ?";
        if (fuzzyTransId.indexOf("%") < 0) {
            fuzzyTransId = "%" + fuzzyTransId + "%";
        }
        return getHibernateTemplate().find(hql, fuzzyTransId);
    }

    public boolean isAffirmedTransaction(String transId) {
        Transaction tran = getTransactionByTranId(transId);
        return isAffirmedTransaction(tran);
    }

    public boolean isAffirmedTransaction(Transaction tran) {
        String transStatus = tran.getTransStatus();
        return Constant.TRANS_STATUS_WAITFORBUYER.equals(transStatus)
                || Constant.TRANS_STATUS_TRANSACTIONSUCCESS.equals(transStatus);
    }

    /**
     * 阌熸枻鎷烽敓阈版枻鎷烽敓鏂ゆ嫹阌熸枻鎷疯幐阌熼桩鍒猴拷
     * 
     * @param transId
     * @param tranStats
     * @return 阌熸枻鎷烽敓鎴潻鎷烽敓鏂ゆ嫹阌熸枻鎷烽敓锟?
     */
    public boolean updateTransStatesByTransId(Transaction transaction) {

        boolean bRetrun = false;
        try {

            getHibernateTemplate().update(transaction);
            bRetrun = true;
        } catch (DataAccessException dateAccess) {
            dateAccess.printStackTrace();
        }
        return bRetrun;
    }

    /**
     * 阌熸枻鎷疯悂阌熸枻鎷烽敓鏂ゆ嫹阌熸嵎镄勬唻鎷烽敓鏂ゆ嫹阌熸枻鎷?阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹钟舵€?
     * 
     * @param transactionId
     * @param downloadState
     * @return 阌熸枻鎷烽敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹钟舵€侀敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹阌燂拷
     */
    public boolean updateDownloadStatesByTransId(Long transactionId,
            String downloadState) {

        Transaction transaction = (Transaction) getHibernateTemplate().get(
                Transaction.class, transactionId);
        transaction.setDownloadState(downloadState);
        getHibernateTemplate().update(transaction);
        return true;
    }

    /**
     * 阌熸枻鎷疯悂阌熸枻鎷峰阌熸枻鎷烽敓鏂ゆ嫹濯掗敓鏂ゆ嫹澹檼阌熸枻鎷烽敓鏂ゆ嫹阌燂拷
     * 
     * @param transId
     * @return 阌熸枻鎷烽敓鏂ゆ嫹涓€阌熸枻鎷烽敓阒惰鎷烽敓鏂ゆ嫹
     */
    public Transaction getSucssTransaction(String transId) {

        Transaction trans = null;
        List list = getHibernateTemplate()
                .find(
                        "from Transaction where transId=? and ((AUDIT_TRANS='0' and (action_seq = 7 or action_seq=4 or action_seq=1)))",
                        new Object[] { transId });

        if (list.size() > 0) {
            trans = (Transaction) list.get(0);
        }
        return trans;
    }

    /**
     * 阃氶敓鏂ゆ嫹阌熼桩璁规嫹阌熸枻鎷烽敓鑴氲鎷烽敓鏂ゆ嫹Transaction
     * 
     * @param orderId
     * @return 阌熸枻鎷烽敓鏂ゆ嫹Transaction阌熸枻鎷烽敓鏂ゆ嫹
     */
    public Transaction getTransactionByOrderId(String orderId) {

        Transaction object = null;

        String hql = "from Transaction where orderId = '" + orderId + "'";

        if (getHibernateTemplate().find(hql).size() > 0) {

            object = (Transaction) getHibernateTemplate().find(hql).get(0);

        }

        return object;
    }

    /**
     * 阌熸枻鎷疯阌熸枻鎷烽敓鏂ゆ嫹钟舵€佷负鎸囬敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹钟舵€侀敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹镞堕敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹鎸囬敓鏂ゆ嫹阌熸枻鎷烽敓鏂ゆ嫹镞堕敓鏂ゆ嫹鎱曢敓鏂ゆ嫹阌燂拷
     * 
     * @param transStatus
     * @param updateTime
     * @return
     */
    public List getTransactionsByTransStatusBeforeUpdateTime(
            String transStatus, Date updateTime) {
        String hql = "from Transaction t where t.updateTime<=? and t.transStatus=?";
        return getHibernateTemplate().find(hql,
                new Object[] { updateTime, transStatus });
    }

    public void updateTran(Transaction tran) {
        getHibernateTemplate().update(tran);
    }

    /**
     * 阌熷彨璁规嫹阌熻鍑ゆ嫹阌熸枻鎷积mail
     */
    public boolean ifSendMail(Account account, String type) {
        if (!Constant.ACCOUNT_STATE_NORMAL.equals(account.getEmStatus())) {
            return false;
        } else {
            String hql = "from AccountMessage t where t.messageCustomization.id = '"
                    + type
                    + "' and t.account.id = '"
                    + account.getId().toString() + "'";
            List list = getHibernateTemplate().find(hql);
            if (list.size() == 0) {
                hql = "from MessageCustomization t where t.setId ='" + type
                        + "'";
                MessageCustomization rule = (MessageCustomization) getHibernateTemplate()
                        .find(hql).get(0);
                if (rule.getEmailDefault().equals(Constant.INSIDE_STATUS_NO)) {
                    return false;
                } else {
                    return true;
                }

            } else {
                AccountMessage am = (AccountMessage) list.get(0);
                if (am.getEmailValidFlag().equals(Constant.INSIDE_STATUS_NO)) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        // return true;
    }

    /**
     * 阌熷彨璁规嫹阌熻鍑ゆ嫹阌熸枻鎷烽敓琛椾紮鎷烽敓鏂ゆ嫹阌燂拷
     */
    public boolean ifSendMobile(Account account, String type) {

        if (!Constant.ACCOUNT_STATE_NORMAL.equals(account.getMobStatus())) {
            return false;
        } else {
            String hql = "from AccountMessage t where t.messageCustomization.id = '"
                    + type
                    + "' and t.account.id = '"
                    + account.getId().toString() + "'";
            List list = getHibernateTemplate().find(hql);
            if (list.size() == 0) {
                hql = "from MessageCustomization t where t.setId ='" + type
                        + "'";
                MessageCustomization rule = (MessageCustomization) getHibernateTemplate()
                        .find(hql).get(0);
                if (rule.getMobileDefault().equals(Constant.INSIDE_STATUS_NO)) {
                    return false;
                } else {
                    return true;
                }

            } else {
                AccountMessage am = (AccountMessage) list.get(0);
                if (am.getMobileValidFlag().equals(Constant.INSIDE_STATUS_NO)) {
                    return false;
                } else {
                    return true;
                }
            }
        }
        // return false;
    }

    public EsPrePayTrans getEsPrePayTransById(String id) {
        String hql = "from EsPrePayTrans t where t.id = " + id;
        return (EsPrePayTrans) getHibernateTemplate().find(hql).get(0);
    }

    public void saveTransactionWithAccountLimit(Transaction trans,
            Account account) throws TransactionException {
        GetTransaction getTran = new GetTransactionImpl();
        String actionType = trans.getActionType().getId().toString();
        TransactionFactory tf = getTran.getTransaction(actionType);
        tf.saveTransaction(trans);

        // 更新交易累计数据
        if(Constant.ACTION_TYPE_D.equals(actionType)) {//只有提现才有金额限制
	        account.setSumAmount(new Double(account.getSumAmount().doubleValue()
	                + trans.getAmount().doubleValue()));
	        if (account.getTranAmount() == null) {
	            account.setTranAmount(new Double(1));
	        } else {
	            account.setTranAmount(new Double(account.getTranAmount()
	                    .doubleValue() + 1));
	        }
	        getMySpaceService().updateAccount(account);
        }
        if(!StringUtil.isStrEmpty(trans.getOrderId())) {//商户编号不为空
        	if(Constant.ACTION_TYPE_C.equals(String.valueOf(trans.getActionType().getId()))
        		&&
        		Constant.ACCOUNT_TYPE_BUYER.equals(trans.getDebit().getAccount().getAccountType())) {//商户编号不为空,搜房间交易,付款方是个人帐户,则可以给付款方加积分
                IScoresService scoreService = ScoresFactory.getScoresService();
                ScoresRules scoresRules = scoreService.getScoresRule(Constant.SCORES_SOURCE_I, String.valueOf(trans.getDebit().getAccount().getId()));//得到商户消费积分的规则
                if(scoresRules != null) {
                	scoreService.saveScoresHistory(String.valueOf(trans.getDebit().getAccount().getId()), scoresRules, trans, null);
                }
        	}
        }

    }
    
    //取出指定用户指定天数内第一笔银行卡充值或电话银行充值成功的交易
    public Transaction getFirstInpourTrans(Long accountId, int days) {
    	Date afterDate = DateUtil.latestOfDate(DateUtil.addDay(new Date(), -days));
    	
    	String hql = "from Transaction t where t.credit.account.id=:id  and t.updateTime>:afterDate";
    	hql += " and (t.actionType.id=" + Constant.ACTION_TYPE_A + " or t.actionType.id=" + Constant.ACTION_TYPE_K + ")";
    	hql += " and t.transStatus=" + Constant.TRANS_STATUS_TRANSACTIONSUCCESS;
    	hql += " order by t.updateTime asc";
    	
    	Query q = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hql);
		q.setParameter("id", accountId);
		q.setParameter("afterDate", afterDate);
		
		List l = q.list();
    	if (l.size() > 0) {
            return (Transaction) l.get(0);
        }
    	return null;
    }
    
    //获取指定用户指定时间之后的交易数量，用于计算该用户的可提现金额
	public int getTransCountPrepareForGetAmountDrawableToSelf(Long accountId, Long subAccountId, Date afterDate) {
		String hSql = null;
		if (subAccountId.longValue()>0) {
			hSql = "select count(*) from TransactionHis t where (t.creditSeq=:id or t.debitSeq=:id)";
		} else {
			hSql = "select count(*) from TransactionHis t, SubAccount s where (t.creditSeq=s.id or t.debitSeq=s.id) and s.account.id=:id";
		}
		hSql += " and t.updateTime>:afterDate";
		hSql += " and t.transStatus in ('1','3','9')";
		
		Query q = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hSql);
		if (subAccountId.longValue()>0) {
			q.setParameter("id", subAccountId);
		} else {
			q.setParameter("id", accountId);
		}
		q.setParameter("afterDate", afterDate);
		
		return ((Long) q.uniqueResult()).intValue();
	}
	
	//获取指定用户指定时间之后的交易列表，用于计算该用户的可提现金额
	public List getTransListPrepareForGetAmountDrawableToSelf(Long accountId, Long subAccountId, Date afterDate, int pageNo, int recordPerPage) {
		String hSql = null;
		if (subAccountId.longValue()>0) {
			hSql = "from TransactionHis t where (t.creditSeq=:id or t.debitSeq=:id)";
		} else {
			hSql = "select t from TransactionHis t, SubAccount s where (t.creditSeq=s.id or t.debitSeq=s.id) and s.account.id=:id";
		}
		hSql += " and t.updateTime>:afterDate";
		hSql += " and t.transStatus in ('1','3','9')";
		hSql += " order by t.transId, t.updateTime desc";
		
		Query q = getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery(hSql);
		if (subAccountId.longValue()>0) {
			q.setParameter("id", subAccountId);
		} else {
			q.setParameter("id", accountId);
		}
		q.setParameter("afterDate", afterDate);
		
		if (pageNo >= 0) {
			pageNo--;
			q.setFirstResult(pageNo * recordPerPage);
			q.setMaxResults(recordPerPage);

		}
		
		return q.list();
	}
}